$(document).ready(function() {
		onStart();
		loadUpcomingCases();
		
		document.addEventListener("backbutton", onBackKeyDown, false);
		function onBackKeyDown(){
			if ($.mobile.activePage.is("#upcomingCasesPage")){
				var r = confirm("Do you want to exit!");
				if (r == true) {
					setTimeout(function(){window.location = 'ExitScreen.html';}, 0)
				} else {
					
				}
             
			}
			else{
            navigator.app.backHistory();
			}

		}
		
		$("#addCase").click(function() {
			if( document.getElementById("plaintiff").value === '' ){
				alert("Plaintiff cannot be empty");
				return;
			}
			if( document.getElementById("respondent").value === ''){
				alert("Respondent cannot be empty");
				return;
			}
			var caseObj = getDummyCaseObject();
			
			caseObj.caseRefNo = document.getElementById("caseRefNo").value;
			caseObj.plaintiff = document.getElementById("plaintiff").value;
			caseObj.respondent = document.getElementById("respondent").value;
			caseObj.caseNote = document.getElementById("caseNote").value;
			caseObj.courtDetails = document.getElementById("courtDetails").value;
			addCase(caseObj);
			document.forms["caseForm"].reset();
			loadAllCases();
		});
		$("#updateCase").click(function() {
			$.mobile.changePage("#updateCasePage");
		});
		$("#showCase").click(function() {
			getAllCases();
		});
		$("#addDate").click(function() {
			if($("#date").val() === ''){
				alert("Date cannot be empty");
				return;
			}
			if($("#dateNote").val() === ''){
				alert("Date Notes cannot be empty");
				return;
			}
			
			var caseDate = document.getElementById("date").value;
			var dateNote = document.getElementById("dateNote").value;
			var caseId = document.getElementById("caseId").value;
			
			if(dateExists(caseId,caseDate)){
				alert("Date already exists of this case !!");
				return;
			}
			addDate(caseId, caseDate, dateNote);
			document.forms["dateForm"].reset();
			getCaseData(caseId);
		});
		$("#activeCases").click(function() {
			loadAllCases();
		});
		$("#addDatePanel").click(function() {
			chooseCase();
		});
		$("#addCasePanel").click(function() {
			$.mobile.changePage("#addCasePage", { transition: "none" });
		});
		$("#upcomingCases").click(function() {
			loadUpcomingCases();
			$.mobile.changePage("#upcomingCasesPage", { transition: "none" });
		});
		
		
	});
	
	function loadAddCasePage() {
			$.mobile.changePage("#addCasePage", { transition: "none" });
	}
	
	
	
	function loadUpcomingCases(){
		var result = upcomingCases();

		$("#upcomingCasesPage").empty();
		
		$("#upcomingCasesPage").append('<div data-role="header" data-position="fixed"><a href="#mypanel" class="ui-btn ui-corner-all ui-icon-bars ui-btn-icon-notext"></a><h1>Upcoming Dates</h1></div><div data-role="main" class="ui-content"><ul id="upcomingCasesList" data-role="listview" data-divider-theme="a" data-inset="true" data-icon="false"></ul></div>');
		
		var tempDate = new Date();
		var today = new Date(tempDate.getFullYear(),tempDate.getMonth(),tempDate.getDate())
		var tomorrow = new Date(today.getFullYear(),today.getMonth(),today.getDate()+1)
		var dateString;
		if(result.length==0){
		
		$("#upcomingCasesPage").append('<div style="text-align:center;"><strong>No Upcoming Dates</br></br>Click the button below to add case</strong></div>');
		}
		for(var i=result.length-1;i>=0;i-- ){
		var date = new Date(result[i].date.getFullYear(),result[i].date.getMonth(),result[i].date.getDate())
		if(date.getTime() == today.getTime() ){
			dateString = "Today";
		}
		else if(date.getTime() == tomorrow.getTime()){
			dateString = "Tomorrow";
		}
		else{
			dateString = result[i].date.toDateString().substring(4);
		}
		$("#upcomingCasesList").append('<li data-role="list-divider">'+dateString+'</li>'); 
		$("#upcomingCasesList").append('<li><a onclick="loadUpdateDate('+result[i].caseId+','+result[i].dateId+')">'+result[i].plaintiff+' vs '+result[i].respondent+'</a></li>'); 
		}
		
		 $("#upcomingCasesPage").append('</div><div data-role="footer" data-position="fixed" style="text-align:center;"><a  class="ui-btn ui-btn-b ui-corner-all ui-icon-plus ui-btn-icon-top" onclick="loadAddCasePage();"><font>Add Case</font></a></div>');
		
			
		$('#bodyId').enhanceWithin();
			
		//$.mobile.changePage("#upcomingCasesPage", { transition: "slide" });	
	}
	
	function loadAllCases() {
	
			var activeCases =JSON.parse(localStorage.getItem("activeCases"));
			$("#allCasesPage").empty();
			 $("#allCasesPage").append('<div data-role="header" data-position="fixed"><a href="#mypanel" class="ui-btn ui-corner-all ui-icon-bars ui-btn-icon-notext"></a><h1> All Cases</h1></div><div data-role="main" class="ui-content"><ul id="allCasesList" data-role="listview" data-inset="true" data-icon="false"></ul></div>')
			for(var i=0;i<activeCases.length;i++ ){
			  var cases = JSON.parse(localStorage.getItem(activeCases[i]));
			  $("#allCasesList").append('<li><a onclick="getCaseData('+activeCases[i]+')">'+cases.plaintiff+' vs '+cases.respondent+'</a></li>'); 
			}
			
			if(activeCases.length==0){
				$("#allCasesPage").append('<div style="text-align:center;"><strong>Click upper left button to add case</strong></div>');
			}
			
			$('#bodyId').enhanceWithin();
			
			$.mobile.changePage("#allCasesPage", { transition: "fade" });	
			
	}
	
	function chooseCase() {
	
			var activeCases =JSON.parse(localStorage.getItem("activeCases"));
			$("#chooseCasePage").empty();
			 $("#chooseCasePage").append('<div data-role="header" data-position="fixed"><a href="#mypanel" class="ui-btn ui-corner-all ui-icon-bars ui-btn-icon-notext"></a><h1>Which Case</h1></div><div data-role="main" class="ui-content"><ul id="chooseCases" data-role="listview" data-inset="true" data-icon="false"></ul></div>')
			for(var i=0;i<activeCases.length;i++ ){
			  var cases = JSON.parse(localStorage.getItem(activeCases[i]));
			  $("#chooseCases").append('<li><a onclick="addDateToPage('+activeCases[i]+')">'+cases.plaintiff+' vs '+cases.respondent+'</a></li>'); 
			}
			if(activeCases.length==0){
				$("#chooseCasePage").append('<div style="text-align:center;"><strong>No case to choose</br>Click upper left button to add case first</strong></div>');
			}
			$('#bodyId').enhanceWithin();
			
			$.mobile.changePage("#chooseCasePage", { transition: "none" });
			
	}
				
	function getCaseData(caseId){
		var caseObj = getCase(caseId);
		var dates = caseObj.dates;
		var courtDetails;
	    $("#viewCasePage").empty();
		$("#viewCasePage").append('<div data-role="header" data-position="fixed"> <a href="#mypanel" class="ui-btn ui-corner-all ui-icon-bars ui-btn-icon-notext"></a><h1>Case Details</h1></div><div data-role="main" id="viewCaseData" class="ui-content">');		
		
		$("#viewCaseData").append("<div class='ui-grid-b'><div class='ui-block-a'><strong>Plaintiff </strong></div><div class='ui-block-b'>"+caseObj.plaintiff+"</div>");
		$("#viewCaseData").append("<div class='ui-grid-b'><div class='ui-block-a'><strong>Respondent  </strong> </div><div class='ui-block-b'> "+caseObj.respondent+"</div>");
		$("#viewCaseData").append("<div class='ui-grid-b'><div class='ui-block-a'><strong>Case Ref No</strong> </div><div class='ui-block-b'> "+caseObj.caseRefNo+"</div>");
		if(caseObj.courtDetails != undefined)
		courtDetails = caseObj.courtDetails;
		else
		courtDetails = "Not available"
		$("#viewCaseData").append("<div class='ui-grid-b'><div class='ui-block-a'><strong>Court Details </strong> </div><div class='ui-block-b'> "+courtDetails+"</div>");
		$("#viewCaseData").append("<div class='ui-grid-b'><div class='ui-block-a'><strong>Case Notes </strong> </div><div class='ui-block-b'>"+caseObj.caseNote.substr(0,50)+"</div>");
		if(caseObj.caseNote.length >25 ){
		$("#viewCaseData").append("<div class='ui-grid-b'><div class='ui-block-a'><strong></strong> </div><div class='ui-block-b'><strong.click edit to see more details</strong></div>");
		}
		
		
		
		
		$("#viewCaseData").append("</br></br><div style='text-align:center;'><strong>Dates</strong></div>");
	$("#viewCaseData").append('<div data-role="controlgroup" data-type="horizontal" style="text-align:center;" data-mini="true"><a href="#" class="ui-btn ui-corner-all">Ascending</a> <a href="#" class="ui-btn ui-corner-all">Descending</a></div>');
		$("#viewCaseData").append('<ul id="allDates" data-role="listview" data-inset="true"  data-icon="false"></ul>');
 
		if(dates.length==0){
				$("#viewCaseData").append('<div style="text-align:center;"><strong>No Date added</strong></div>');
		}
		for (var counter = 0; counter < dates.length; counter++) {
				$("#allDates").append('<li><a onclick="loadUpdateDate('+caseId+','+dates[counter].dateId+')">'+(new Date(dates[counter].caseDate)).toDateString().substring(4)+' </br> '+dates[counter].dateNote+'</a></li>'); 
		}
	

	    $("#viewCasePage").append('</div><div data-role="footer" data-position="fixed" style="text-align:center;"><a id="addDateButton" data-icon="plus" data-theme="b" onclick="addDateToPage('+caseId+')">Add Date</a>&nbsp;&nbsp;<a id="loadUpdateCasePageButton" data-icon="edit" data-theme="b" onclick="loadUpdateCasePage('+caseId+')">Edit</a>&nbsp;&nbsp;<a id="deleteCaseButton" data-theme="b" data-icon="delete" onclick="deleteCaseImpl('+caseId+')">Delete</a></div>');
		
		$('#bodyId').enhanceWithin();
		$.mobile.changePage("#viewCasePage",{ transition: "none" });
		
	
	}
	function addDateToPage(caseId){
	var caseData = getCase(caseId);
	var dates = caseData.dates;
	$("#caseInfo").html("");
	$("#caseInfo").html("</br><strong>"+caseData.plaintiff+" vs "+caseData.respondent+"</strong>");
	
	if(dates.length != 0){
	$("#caseInfo").append("</br></br>");
	$("#caseInfo").append("<strong>Previous Date :&nbsp;</strong>");
	$("#caseInfo").append(new Date((dates[dates.length-1].caseDate)).toDateString().substring(4));
	}

	$("#caseInfo").append("<input type='hidden' id='caseId' value='"+caseId+"' >");
	$.mobile.changePage("#addDatePage", { transition: "none" });
	}
	function deleteCaseImpl(caseId){
		var option = confirm("Do you want to delete the case ?")
	
		if(option == true){
			deleteCase(caseId);
			loadAllCases();
		}
	}
	function loadUpdateCasePage(caseId){
	
		
		var caseObj = getCase(caseId);
		$("#caseRefNoUpdate").val(caseObj.caseRefNo);
		$("#plaintiffUpdate").val(caseObj.plaintiff);
		$("#respondentUpdate").val(caseObj.respondent);
		$("#caseNoteUpdate").val(caseObj.caseNote);
		$("#updateCaseButton").attr("onclick","updateCaseImpl("+caseId+")");
		$.mobile.changePage("#updateCasePage", { transition: "none" });
	
	
	}
	function updateCaseImpl(caseId){
	
			var caseObj = getDummyCaseObject();
			if( document.getElementById("plaintiffUpdate").value === '' ){
				alert("Plaintiff cannot be empty");
				return;
			}
			if( document.getElementById("respondentUpdate").value === ''){
				alert("Respondent cannot be empty");
				return;
			}
			
			caseObj.caseRefNo = document.getElementById("caseRefNoUpdate").value;
			caseObj.plaintiff = document.getElementById("plaintiffUpdate").value;
			caseObj.respondent = document.getElementById("respondentUpdate").value;
			caseObj.caseNote = document.getElementById("caseNoteUpdate").value;
			caseObj.courtDetails = document.getElementById("courtDetailsUpdate").value;
			
			updateCase(caseId,caseObj);
			loadAllCases();
	}
	function getDateData(caseId,dateId){
		
		var dateObj = getDate(caseId,dateId)
		$("#viewDateData").html("");
		$("#viewDateData").append("<table><tr><td>Date</td><td>:"+(new Date(dateObj.caseDate)).toDateString()+"</td></tr>");
		$("#viewDateData").append("<tr><td>Date Notes</td><td>:"+dateObj.dateNote+"</td></tr></table>");
		$("#loadUpdateDatePage").attr("onclick","loadUpdateDate("+caseId+","+dateId+")");
		$("#deleteDateButton").attr("onclick","deleteDateImpl("+caseId+","+dateId+")");
		$.mobile.changePage("#datePage", { transition: "none" });
	
	}
	function loadUpdateDate(caseId,dateId){
		
		var caseData = getCase(caseId);
		
		$("#caseInfoUpdatePage").html("");
		$("#caseInfoUpdatePage").html("<strong>"+caseData.plaintiff+" vs "+caseData.respondent+"</strong>");
	
		var dateObj = getDate(caseId,dateId);
		$("#updateDate").val(dateObj.caseDate);
		$("#updateDateNote").val(dateObj.dateNote);
		$("#updateDateButton").attr("onclick","updateDateImpl("+caseId+","+dateId+")");
		$("#deleteDateButton").attr("onclick","deleteDateImpl("+caseId+","+dateId+")");
		$.mobile.changePage("#updateDatePage", { transition: "none" });
		
	}
	function deleteDateImpl(caseId,dateId){
	  var option = confirm("Do you want to delete the date ?")
	
		if(option == true){
			
			deleteDate(caseId,dateId);
			getCaseData(caseId);
		}
	}
	function updateDateImpl(caseId,dateId){
		if($("#updateDate").val() === ''){
			alert("Date cannot be empty");
			return;
		}
		try{
		var d = new Date($("#updateDate").val());
		}
		catch(e){
		   alert("Please enter date in mm/dd/yyyy format");
		   return;
		}
		if($("#updateDateNote").val() === ''){
			alert("Date Notes cannot be empty");
			return;
		}
		
		var caseDate = $("#updateDate").val();
		var dateNote = $("#updateDateNote").val();
		updateDate(caseId,dateId,caseDate,dateNote);
		getCaseData(caseId);
	}
	function loadSearchPage(){
			$("#searchPage").empty();
			 $("#searchPage").append('<div data-role="header" data-position="fixed"><a href="#mypanel" class="ui-btn ui-corner-all ui-icon-bars ui-btn-icon-notext"></a><h1>Search</h1></div><div data-role="main" class="ui-content"><ul id="searchList" data-role="listview" data-inset="true" data-filter="true" data-filter-reveal="true" data-filter-placeholder="Search..." data-icon="false"></ul></div>');
			var cases = setCasesInAscendingOrder();
			
			for(var i=0;i<cases.length;i++ ){
			  var dateObj = getDate(cases[i].caseId,cases[i].dateId);
			  
			  $("#searchList").append('<li><a onclick="getCaseData('+cases[i].caseId+')">'+cases[i].plaintiff+' vs '+cases[i].respondent+'</br>'+cases[i].date.toDateString()+'</br>'+dateObj.dateNote+'</a></li>'); 
			}
			
			$('#bodyId').enhanceWithin();
			
			$.mobile.changePage("#searchPage", { transition: "flow" });
	
	
	
	}
	
	
	